package com.yitiao.data_algorithms.leetcode.editor.cn;

import java.util.HashMap;

class LongestRepeatingCharacterReplacement {
    // 2022-11-07 17:39:11
    public static void main(String[] args) {
        Solution solution = new LongestRepeatingCharacterReplacement().new Solution();
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int characterReplacement(String s, int k) {
            if (s.length() == 1) return 1;

            HashMap<Character, Integer> map = new HashMap<>();
            int left = 0;
            int right = 0;
            int max = 0;
            while (right < s.length()) {
                // 记录每个元素出现的次数
                map.put(s.charAt(right), map.getOrDefault(s.charAt(right), 0) + 1);
                // max 计算窗口内出现次数最多的元素
                max = Math.max(max, map.get(s.charAt(right)));
                // 如果需要替换的元素大于 k ，左指针右移，缩小窗口
                if ((right - left - max + 1) > k) {
                    if (max==map.get(s.charAt(left))){
                        max--;
                    }
                    map.put(s.charAt(left), map.get(s.charAt(left)) - 1);
                    left++;
                }
                right++;
            }
            return right - left;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}